<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? $t('workReports.dialog.edit') : $t('workReports.dialog.create')"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent
    >
      <el-form-item :label="$t('workReports.dialog.form.date')" prop="date">
        <el-date-picker
          v-model="form.date"
          type="date"
          :placeholder="$t('workReports.dialog.form.placeholders.selectDate')"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item :label="$t('workReports.dialog.form.title')" prop="title">
        <el-input
          v-model="form.title"
          :placeholder="$t('workReports.dialog.form.placeholders.enterTitle')"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item :label="$t('workReports.dialog.form.category')" prop="categoryId">
        <el-select
          v-model="form.categoryId"
          :placeholder="$t('workReports.dialog.form.placeholders.selectCategory')"
          clearable
          style="width: 100%"
        >
          <el-option-group :label="$t('workReports.dialog.form.categories.system')">
            <el-option
              v-for="category in systemCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            >
              <span class="category-option">
                <el-icon :color="category.color">
                  <component :is="getCategoryIcon(category.icon)" />
                </el-icon>
                {{ category.name }}
              </span>
            </el-option>
          </el-option-group>
          <el-option-group v-if="userCategories.length > 0" :label="$t('workReports.dialog.form.categories.custom')">
            <el-option
              v-for="category in userCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            >
              <span class="category-option">
                <el-icon :color="category.color">
                  <component :is="getCategoryIcon(category.icon)" />
                </el-icon>
                {{ category.name }}
              </span>
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('workReports.dialog.form.status')" prop="status">
            <el-select v-model="form.status" :placeholder="$t('workReports.dialog.form.placeholders.selectStatus')" style="width: 100%">
              <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              >
                <el-tag :type="getStatusType(status.value)" size="small">
                  {{ status.label }}
                </el-tag>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('workReports.dialog.form.priority')" prop="priority">
            <el-select v-model="form.priority" :placeholder="$t('workReports.dialog.form.placeholders.selectPriority')" style="width: 100%">
              <el-option
                v-for="priority in priorityOptions"
                :key="priority.value"
                :label="priority.label"
                :value="priority.value"
              >
                <el-tag :type="getPriorityType(priority.value)" size="small">
                  {{ priority.label }}
                </el-tag>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="$t('workReports.dialog.form.timeSpent')" prop="timeSpent">
        <el-input-number
          v-model="form.timeSpent"
          :min="0"
          :max="1440"
          :step="15"
          :placeholder="$t('workReports.dialog.form.placeholders.timeSpentMinutes')"
          style="width: 100%"
        />
        <span class="time-hint">{{ $t('workReports.dialog.form.hints.timeSpent') }}</span>
      </el-form-item>

      <el-form-item :label="$t('workReports.dialog.form.tags')" prop="tags">
        <el-select
          v-model="form.tags"
          multiple
          filterable
          allow-create
          default-first-option
          :placeholder="$t('workReports.dialog.form.placeholders.addTags')"
          style="width: 100%"
        >
          <el-option
            v-for="tag in commonTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('workReports.dialog.form.content')" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="4"
          :placeholder="$t('workReports.dialog.form.placeholders.enterContent')"
          maxlength="5000"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('workReports.dialog.actions.cancel') }}</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? $t('workReports.dialog.actions.update') : $t('workReports.dialog.actions.save') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { useWorkReportStore } from '@/stores/workReportStore'
import type { WorkRecord, WorkCategory } from '@/types/workReport'
import { STATUS_OPTIONS, PRIORITY_OPTIONS, WorkRecordStatus, WorkRecordPriority } from '@/types/workReport'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Folder, Files, Tools, ChatDotRound, Reading, Document, Monitor } from '@element-plus/icons-vue'

// Props
interface Props {
  modelValue: boolean
  record?: WorkRecord | null
  categories: WorkCategory[]
}

const props = withDefaults(defineProps<Props>(), {
  record: null,
  categories: () => [] // 添加默认值，防止undefined导致的filter错误
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

const { t } = useI18n()
const workReportStore = useWorkReportStore()

// 国际化选项
const statusOptions = computed(() => [
  { label: t('workReports.dialog.form.statusOptions.pending'), value: WorkRecordStatus.PENDING, color: '#909399' },
  { label: t('workReports.dialog.form.statusOptions.inProgress'), value: WorkRecordStatus.IN_PROGRESS, color: '#409EFF' },
  { label: t('workReports.dialog.form.statusOptions.completed'), value: WorkRecordStatus.COMPLETED, color: '#67C23A' },
  { label: t('workReports.dialog.form.statusOptions.cancelled'), value: WorkRecordStatus.CANCELLED, color: '#F56C6C' }
])

const priorityOptions = computed(() => [
  { label: t('workReports.dialog.form.priorityOptions.low'), value: WorkRecordPriority.LOW, color: '#909399' },
  { label: t('workReports.dialog.form.priorityOptions.medium'), value: WorkRecordPriority.MEDIUM, color: '#409EFF' },
  { label: t('workReports.dialog.form.priorityOptions.high'), value: WorkRecordPriority.HIGH, color: '#E6A23C' },
  { label: t('workReports.dialog.form.priorityOptions.urgent'), value: WorkRecordPriority.URGENT, color: '#F56C6C' }
])

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)

// 表单数据
const form = ref({
  date: '',
  title: '',
  content: '',
  categoryId: null as number | null,
  status: WorkRecordStatus.PENDING,
  priority: WorkRecordPriority.MEDIUM,
  timeSpent: 0,
  tags: [] as string[]
})

// 常用标签
const commonTags = ref([
  '开发', '测试', '会议', '学习', '文档', '修复', '优化', '部署', '设计', '讨论'
])

// 表单验证规则
const rules = computed<FormRules>(() => ({
  date: [
    { required: true, message: t('workReports.dialog.form.rules.dateRequired'), trigger: 'change' }
  ],
  title: [
    { required: true, message: t('workReports.dialog.form.rules.titleRequired'), trigger: 'blur' },
    { min: 1, max: 200, message: t('workReports.dialog.form.rules.titleLength'), trigger: 'blur' }
  ],
  status: [
    { required: true, message: t('workReports.dialog.form.rules.statusRequired'), trigger: 'change' }
  ],
  priority: [
    { required: true, message: t('workReports.dialog.form.rules.priorityRequired'), trigger: 'change' }
  ],
  timeSpent: [
    { type: 'number', min: 0, max: 1440, message: t('workReports.dialog.form.rules.timeSpentRange'), trigger: 'blur' }
  ]
}))

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.record)

const systemCategories = computed(() =>
  (props.categories || []).filter(cat => cat.isSystem)
)

const userCategories = computed(() =>
  (props.categories || []).filter(cat => !cat.isSystem)
)

// 重置表单
const resetForm = () => {
  form.value = {
    date: new Date().toISOString().split('T')[0], // 默认今天
    title: '',
    content: '',
    categoryId: null,
    status: WorkRecordStatus.PENDING,
    priority: WorkRecordPriority.MEDIUM,
    timeSpent: 0,
    tags: []
  }
  formRef.value?.clearValidate()
}

// 监听记录变化，初始化表单
watch(
  () => props.record,
  (newRecord) => {
    if (newRecord) {
      form.value = {
        date: newRecord.date,
        title: newRecord.title,
        content: newRecord.content || '',
        categoryId: newRecord.categoryId || null,
        status: newRecord.status,
        priority: newRecord.priority,
        timeSpent: newRecord.timeSpent || 0,
        tags: newRecord.tags || []
      }
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

// 监听对话框显示状态
watch(visible, (newVisible) => {
  if (newVisible) {
    nextTick(() => {
      if (!props.record) {
        resetForm()
      }
    })
  }
})

// 获取分类图标
const getCategoryIcon = (icon: string) => {
  const iconMap: Record<string, any> = {
    folder: Folder,
    code: Files,
    bug: Tools,
    meeting: ChatDotRound,
    study: Reading,
    document: Document,
    server: Monitor
  }
  return iconMap[icon] || Folder
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': 'info',
    'IN_PROGRESS': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取优先级类型
const getPriorityType = (priority: string) => {
  const priorityMap: Record<string, string> = {
    'LOW': 'info',
    'MEDIUM': 'primary',
    'HIGH': 'warning',
    'URGENT': 'danger'
  }
  return priorityMap[priority] || 'primary'
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (isEdit.value && props.record) {
      // 更新记录
      await workReportStore.updateRecord(props.record.id!, form.value)
    } else {
      // 创建记录
      await workReportStore.createRecord(form.value)
    }

    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 处理关闭
const handleClose = () => {
  if (submitting.value) return
  visible.value = false
}
</script>

<style scoped lang="scss">
.category-option {
  display: flex;
  align-items: center;
  gap: 6px;
}

.time-hint {
  margin-left: 8px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-textarea__inner) {
  resize: vertical;
}
</style>
